import ij.ImagePlus;
import ij.process.ImageConverter;
import ij.process.ImageProcessor;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.imageio.ImageIO;

public class Main {
	
	private static int counter = 0;

	public static void main(String[] args) {
		BrainBuddy buddy = new BrainBuddy();
		buddy.play();
	}

	// prints the logs on the screen with time it is called
	public static void log(String log) {
		Date date = new Date();
		long time = date.getTime();
		System.out.println(time + ": " + log);
	}

	// write image to the file for test
	public static void writeImage(BufferedImage image) {
		/*
		try {
		    File outputfile = new File("capture"+counter+".png");
		    ImageIO.write(image, "png", outputfile);
		    counter++;
		} catch (IOException e) {
		    Main.log(e.getMessage());
		    System.exit(-1);
		}
		*/
		
		
	}
	
	/*
	 * This function converts image to 8 bit color and then process and find the edges in the game
	 */
	public static BufferedImage processImage(BufferedImage image) {
		
		ImagePlus imagePlus = new ImagePlus("base screen", image);
		ImageConverter converter = new ImageConverter(imagePlus);
		converter.convertToGray8();
		ImageProcessor processor = imagePlus.getProcessor();
		
		//processor.findEdges();
		//image = imagePlus.getBufferedImage();
		
		return image;
	}
	
	/*
	 * make binary
	 */
	public static BufferedImage makeBinary(BufferedImage image) {
		
		ImagePlus imp = new ImagePlus("base screen", image);
		
		double minThreshold, maxThreshold;
		
		boolean fill1, fill2;
		
		imp.killRoi();
		ImageProcessor ip = imp.getProcessor();
		ip.resetBinaryThreshold();

		fill1 = fill2  = true;

		int type = imp.getType();

		if (type != ImagePlus.GRAY8) {
			ImageConverter converter = new ImageConverter(imp);
			converter.convertToGray8();
			//convertToByte(imp);
		}
		
		ip = imp.getProcessor();

		//auto threshold
		ip.setAutoThreshold(ImageProcessor.ISODATA2, ImageProcessor.NO_LUT_UPDATE);
        minThreshold = ip.getMinThreshold();
        maxThreshold = ip.getMaxThreshold();

		int fcolor, bcolor;
		ip.resetThreshold();
		int savePixel = ip.getPixel(0, 0);
	
		ip.setColor(Color.black);
		
		ip.drawPixel(0, 0);
		fcolor = ip.getPixel(0, 0);
	
		ip.setColor(Color.white);
		ip.drawPixel(0, 0);
		bcolor = ip.getPixel(0, 0);
		//ip.setColor(Toolbar.getForegroundColor());
		ip.putPixel(0, 0, savePixel);

		int[] lut = new int[256];
		for (int i = 0; i < 256; i++) {
			if (i >= minThreshold && i <= maxThreshold)
				lut[i] = fill1 ? fcolor : (byte) i;
			else {
				lut[i] = fill2 ? bcolor : (byte) i;
			}
		}
		
		ip.applyTable(lut);
		
		if (fill1 = true
				&& fill2 == true
				&& ((fcolor == 0 && bcolor == 255) || (fcolor == 255 && bcolor == 0)))
			imp.getProcessor().setThreshold(fcolor, fcolor,
					ImageProcessor.NO_LUT_UPDATE);
		
		return imp.getBufferedImage();
	}
}
